package com.zhidisoft.system.dao.impl;

import java.util.List;







import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.zhidisoft.base.dao.impl.BaseDaoImpl;
import com.zhidisoft.system.dao.IFunctionDao;
import com.zhidisoft.system.entity.Function;

/**
 * 功能模块数据库操作实现
 * @author Lu Jianliang
 *
 */
@SuppressWarnings("all")
@Repository
public class FunctionDaoImpl extends BaseDaoImpl<Function, String> implements IFunctionDao {

	
	@Override
	public List<Function> findFunctions(Integer funcType, String... roleIds) {
		String hql = "select distinct f from Function f inner join fetch f.roles r where f.status = 1 and f.funcType=:type and r.id in(:ids) order by f.sortNum";
		Query query = session().createQuery(hql);
		query.setParameter("type", funcType);
		query.setParameterList("ids", roleIds);
		return query.list();
	}

	@Override
	public List<Function> findAll() {
		String hql = "from Function f left join fetch f.parent left join fetch f.createUser left join fetch f.updateUser where f.status=1 order by f.sortNum";
		return this.find(hql, new String[]{});
	}

	@Override
	public List<Function> findByRoleIds(String[] roleIds) {
		String hql = "from Function f left join fetch f.parent left join fetch f.createUser left join fetch f.updateUser inner join  fetch f.roles r where f.status=1 and r.id in (:ids) order by sortNum";
		
		return session().createQuery(hql).setParameterList("ids", roleIds).list();
	}

	@Override
	public List<Function> findFunctions(Integer funcType) {
		String hql = "select distinct f from Function f left join fetch f.children c where f.funcType=? order by f.sortNum";
		return this.find(hql, funcType);
	}

	@Override
	public List<Function> findByParentId(Integer funcType, String parentId) {
		String hql = "";
		if(StringUtils.isBlank(parentId)){
			hql = "select distinct f from Function f left join fetch f.children c where f.funcType=? and c.funcType=? and f.parent is null ";
			return this.find(hql,funcType,funcType);
		}else{
			hql = "select distinct f from Function f left join fetch f.children c where f.funcType=? and (c is null or c.funcType=?) and f.parent.id=?";
			return this.find(hql,funcType,funcType,parentId);
		}
	}
	
	

}
